package com.ssy.lingxi.enhance.serviceimpl.supplier;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.enhance.constant.*;
import com.ssy.lingxi.enhance.entity.InnerWorkflowRecordDO;
import com.ssy.lingxi.enhance.entity.ProduceNoticeOrderDO;
import com.ssy.lingxi.enhance.entity.ProduceNoticeOrderDetailDO;
import com.ssy.lingxi.enhance.entity.QProduceNoticeOrderDO;
import com.ssy.lingxi.enhance.handler.async.MessageAsyncService;
import com.ssy.lingxi.enhance.handler.async.OrderAsyncService;
import com.ssy.lingxi.enhance.handler.async.ReportAsyncService;
import com.ssy.lingxi.enhance.handler.jpa.QueryDslUtil;
import com.ssy.lingxi.enhance.model.dto.CommonIdListDTO;
import com.ssy.lingxi.enhance.model.dto.ExamDTO;
import com.ssy.lingxi.enhance.model.qo.ProduceNoticeOrderQO;
import com.ssy.lingxi.enhance.model.vo.ProduceNoticeOrderListVO;
import com.ssy.lingxi.enhance.repository.InnerWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderDetailRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderRepository;
import com.ssy.lingxi.enhance.service.supplier.SupplierToBeSecondExamService;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.report.api.enums.EnhanceSupplierOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessTaskStatusEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 加工能力 - 指派生产通知单(供应商) - 待审核生产通知单(二级) - 业务实现层
 * @author fhj
 * @date 2020/10/20
 * @version 2.0.0
 */
@Slf4j
@Service
public class SupplierToBeSecondExamServiceImpl implements SupplierToBeSecondExamService {

    @Resource
    private ProcessFeign processFeign;
    @Resource
    private QueryDslUtil queryDslUtil;
    @Resource
    private ProduceNoticeOrderRepository produceNoticeOrderRepository;
    @Resource
    private ProduceNoticeOrderDetailRepository produceNoticeOrderDetailRepository;
    @Resource
    private InnerWorkflowRecordRepository innerWorkflowRecordRepository;
    @Resource
    private ReportAsyncService reportAsyncService;
    @Resource
    private OrderAsyncService orderAsyncService;
    @Resource
    private MessageAsyncService messageAsyncService;

    /**
     * 列表
     * */
    @Override
    public Wrapper<PageData<ProduceNoticeOrderListVO>> list(ProduceNoticeOrderQO qo, UserLoginCacheDTO user) {
        //查询表实体 - 生产通知单
        QProduceNoticeOrderDO pno = QProduceNoticeOrderDO.produceNoticeOrderDO;

        //查询条件构造 - 必要条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(pno.supplierMemberId.eq(user.getMemberId()));
        predicates.and(pno.supplierRoleId.eq(user.getMemberRoleId()));
        predicates.and(pno.outerStatus.eq(PNOOuterStatusEnum.TO_BE_SUBMIT.getCode()));
        predicates.and(pno.supplierInnerStatus.eq(PNOSupplierInnerStatusEnum.TO_BE_EXAM2.getCode()));

        return Wrapper.success(queryDslUtil.getSupplierPNOList(qo, pno, predicates));
    }

    /**
     * 审核
     * */
    @Override
    @Transactional
    public Wrapper<Void> exam(ExamDTO dto, UserLoginCacheDTO user) {
        //如果审核不通过时, 校验审核不通过原因是否为空
        if(dto.getStatus().equals(ExamStatusEnum.NO.getCode()) && StringUtils.isBlank(dto.getCause())) {
            return Wrapper.fail(ResponseCode.ENHANCE_VALIDATE_DISAGREE_REASON_CAN_NOT_BE_EMPTY);
        }

        //根据ID获取生产通知单详情
        ProduceNoticeOrderDO produceNoticeOrder = produceNoticeOrderRepository.findById(dto.getId()).orElse(null);
        if(produceNoticeOrder == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_SUPPLIER_EXAM2.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_EXAM_INNER_STATUS_AS_TO_BE_SUPPLIER_EXAM2);
        }

        //如果通知单来源为加工订单且审核是不通过的话, 需要更新订单服务里的订单商品已加工数量（根据生产通知单明细将新增时加上去的已加工数量再减回去, 保持数量一致性）
        if(produceNoticeOrder.getSource().equals(SourceEnum.ORDER.getCode()) && dto.getStatus().equals(ExamStatusEnum.NO.getCode())) {
            List<ProduceNoticeOrderDetailDO> details = produceNoticeOrderDetailRepository.findByProduceNoticeOrderId(dto.getId());
            orderAsyncService.updateOrderProductProcessNum(details, Boolean.FALSE);
        }

        //调用工作流服务 -> 执行供应商内部流程
        TaskExecuteVO taskExecuteVO = new TaskExecuteVO();
        taskExecuteVO.setMemberId(produceNoticeOrder.getSupplierMemberId());
        taskExecuteVO.setRoleId(produceNoticeOrder.getSupplierRoleId());
        taskExecuteVO.setDataId(produceNoticeOrder.getId());
        taskExecuteVO.setTaskId(produceNoticeOrder.getSupplierInnerTaskId());
        taskExecuteVO.setAgree(dto.getStatus());
        taskExecuteVO.setProcessKey(produceNoticeOrder.getSupplierInnerProcessKey());
        Wrapper<SimpleTaskCompleteVO> wrapper = processFeign.completeSimpleTask(taskExecuteVO);
        if(ResponseCode.SUCCESS.getCode() == wrapper.getCode()) {
            //记录供应商内部工作流记录
            InnerWorkflowRecordDO innerWorkflowRecord = new InnerWorkflowRecordDO();
            innerWorkflowRecord.setProduceNoticeOrderId(produceNoticeOrder.getId());
            innerWorkflowRecord.setUserId(user.getUserId());
            innerWorkflowRecord.setMemberId(user.getMemberId());
            innerWorkflowRecord.setRoleId(user.getMemberRoleId());
            innerWorkflowRecord.setType(RoleTypeEnum.SUPPLIER.getCode());
            innerWorkflowRecord.setStep(produceNoticeOrder.getSupplierInnerStatus());
            innerWorkflowRecord.setOperator(user.getUserName());
            innerWorkflowRecord.setDepartment(user.getUserOrgName());
            innerWorkflowRecord.setJobTitle(user.getUserJobTitle());
            innerWorkflowRecord.setStatus(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "待提交" : "审核不通过（二级）");
            innerWorkflowRecord.setOperate("审核生产通知单（二级）");
            innerWorkflowRecord.setOperateTime(System.currentTimeMillis());
            innerWorkflowRecord.setOpinion(dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ? "同意" : "不同意");
            innerWorkflowRecordRepository.saveAndFlush(innerWorkflowRecord);

            //更新状态、供应商内部状态、供应商内部任务ID
            produceNoticeOrder.setStatus(
                    dto.getStatus().equals(ExamStatusEnum.YES.getCode()) ?
                            PNOAllStatusEnum.TO_BE_SUPPLIER_SUBMIT.getCode() : PNOAllStatusEnum.SUPPLIER_NOT_PASSED2.getCode()
            );
            produceNoticeOrder.setSupplierInnerStatus(wrapper.getData().getStatus());
            produceNoticeOrder.setSupplierInnerTaskId(wrapper.getData().getTaskId());
            produceNoticeOrder.setCause(dto.getCause());
            produceNoticeOrderRepository.saveAndFlush(produceNoticeOrder);
        }else {
            log.error("工作流服务异常:" + wrapper.getMessage());
            throw new BusinessException(ResponseCode.ENHANCE_WORKFLOW_ERROR);
        }

        //调用报表服务、消息服务 -> 新增操作通知、发送系统消息，审核不通过的话不需要发送系统消息（如果调用过程出现异常, 无需回滚, 直接catch打印日志正常返回。）
        if(dto.getStatus().equals(ExamStatusEnum.YES.getCode())) {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_SUPPLIER.getCode(),
                    EnhanceSupplierOperateTypeEnum.TO_BE_COMMIT.getCode(),  1L,
                    EnhanceSupplierOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L
            );
            messageAsyncService.sendSystemMessage(user.getMemberId(), user.getMemberRoleId(),
                    MessageTemplateCode.production_order_submit, Stream.of(produceNoticeOrder.getNoticeNo(), produceNoticeOrder.getSummary()).collect(Collectors.toList())
            );
        }else {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_SUPPLIER.getCode(),
                    null,  null,
                    EnhanceSupplierOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L
            );
        }

        return Wrapper.success();
    }

    /**
     * 批量审核通过
     * */
    @Override
    @Transactional
    public Wrapper<Void> batchExamPass(CommonIdListDTO dto, UserLoginCacheDTO user) {
        //根据ID集合获取生产通知单集合
        List<ProduceNoticeOrderDO> produceNoticeOrderList = produceNoticeOrderRepository.findAllById(dto.getIdList());

        //初始化变量：审核通过成功数量（新增操作通知）、SystemMessageRequest集合（发送系统消息）
        Long flag = 0L;
        List<SystemMessageRequest> systemMessageRequestList = new ArrayList<>();

        //校验
        if(CollectionUtil.isEmpty(produceNoticeOrderList)) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(produceNoticeOrderList.stream().anyMatch(a -> !a.getStatus().equals(PNOAllStatusEnum.TO_BE_SUPPLIER_EXAM2.getCode()))) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_EXAM_INNER_STATUS_AS_TO_BE_SUPPLIER_EXAM2);
        }

        //循环调用工作流服务, 调用成功时更新生产通知单和新增内部工作流记录, 调用失败直接返回, 不需要抛出异常, 因为前面调用成功的不需要回滚。
        for(ProduceNoticeOrderDO p:produceNoticeOrderList) {
            //调用工作流服务 -> 执行供应商内部流程
            TaskExecuteVO taskExecuteVO = new TaskExecuteVO();
            taskExecuteVO.setMemberId(p.getSupplierMemberId());
            taskExecuteVO.setRoleId(p.getSupplierRoleId());
            taskExecuteVO.setDataId(p.getId());
            taskExecuteVO.setTaskId(p.getSupplierInnerTaskId());
            taskExecuteVO.setAgree(ProcessTaskStatusEnum.AGREE.getCode());
            taskExecuteVO.setProcessKey(p.getSupplierInnerProcessKey());
            Wrapper<SimpleTaskCompleteVO> wrapper = processFeign.completeSimpleTask(taskExecuteVO);
            if(ResponseCode.SUCCESS.getCode() == wrapper.getCode()) {
                //记录供应商内部工作流记录
                InnerWorkflowRecordDO innerWorkflowRecord = new InnerWorkflowRecordDO();
                innerWorkflowRecord.setProduceNoticeOrderId(p.getId());
                innerWorkflowRecord.setUserId(user.getUserId());
                innerWorkflowRecord.setMemberId(user.getMemberId());
                innerWorkflowRecord.setRoleId(user.getMemberRoleId());
                innerWorkflowRecord.setType(RoleTypeEnum.SUPPLIER.getCode());
                innerWorkflowRecord.setStep(p.getSupplierInnerStatus());
                innerWorkflowRecord.setOperator(user.getUserName());
                innerWorkflowRecord.setDepartment(user.getUserOrgName());
                innerWorkflowRecord.setJobTitle(user.getUserJobTitle());
                innerWorkflowRecord.setStatus("待提交");
                innerWorkflowRecord.setOperate("审核生产通知单（二级）");
                innerWorkflowRecord.setOperateTime(System.currentTimeMillis());
                innerWorkflowRecord.setOpinion("同意");
                innerWorkflowRecordRepository.saveAndFlush(innerWorkflowRecord);

                //更新状态、供应商内部状态、供应商内部任务ID
                p.setStatus(PNOAllStatusEnum.TO_BE_SUPPLIER_SUBMIT.getCode());
                p.setSupplierInnerStatus(wrapper.getData().getStatus());
                p.setSupplierInnerTaskId(wrapper.getData().getTaskId());
                produceNoticeOrderRepository.saveAndFlush(p);

                //每保存一次，新增操作通知、发送系统消息各加一
                flag++;
                SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
                systemMessageRequest.setMemberId(p.getSupplierMemberId());
                systemMessageRequest.setRoleId(p.getSupplierRoleId());
                systemMessageRequest.setMessageNotice(MessageTemplateCode.production_order_submit);
                systemMessageRequest.setParams(Stream.of(p.getNoticeNo(), p.getSummary()).collect(Collectors.toList()));
                systemMessageRequestList.add(systemMessageRequest);
            }else {
                //保存成功的生产通知单需要调用报表服务和消息服务 -> 新增操作通知、批量发送系统消息
                if(flag > 0) {
                    reportAsyncService.addOperateNotice(
                            user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_SUPPLIER.getCode(),
                            EnhanceSupplierOperateTypeEnum.TO_BE_COMMIT.getCode(),  flag,
                            EnhanceSupplierOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), flag
                    );
                    messageAsyncService.batchSendSystemMessage(systemMessageRequestList);
                }
                log.error("工作流服务异常:" + wrapper.getMessage());
                return Wrapper.fail(ResponseCode.ENHANCE_WORKFLOW_ERROR);
            }
        }

        //调用报表服务、消息服务 -> 新增操作通知和批量发送系统消息（如果调用过程出现异常, 无需回滚, 直接catch打印日志正常返回。）
        reportAsyncService.addOperateNotice(
                user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_SUPPLIER.getCode(),
                EnhanceSupplierOperateTypeEnum.TO_BE_COMMIT.getCode(),  flag,
                EnhanceSupplierOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), flag
        );
        messageAsyncService.batchSendSystemMessage(systemMessageRequestList);

        return Wrapper.success();
    }
}
